<template>
   <div class="app-container">
      <div class="p4">
         <FaSearchBar :show-toggle="false">
            <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="80px">
               <el-form-item label="模块名称" prop="name">
                  <el-input v-model="queryParams.name" placeholder="请输入模块名称" clearable style="width: 150px"
                     @keyup.enter="handleQuery" />
               </el-form-item>
               <el-form-item label="状态" prop="status">
                  <el-select v-model="queryParams.status" placeholder="菜单状态" clearable style="width: 150px">
                     <el-option v-for="dict in sys_common_status" :key="dict.value" :label="dict.label"
                        :value="dict.value" />
                  </el-select>
               </el-form-item>
               <el-form-item>
                  <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                  <el-button @click="resetQuery">重置</el-button>
               </el-form-item>
            </el-form>
         </FaSearchBar>
         <el-divider border-style="dashed" style="margin:0px 0px 20px 0px" />

         <el-space wrap>
            <el-button type="primary" icon="Plus" @click="handleAdd" v-auth="['app:menu$add']">新增</el-button>
            <el-button icon="Sort" @click="toggleExpandAll">展开/折叠</el-button>
         </el-space>

         <el-table v-if="refreshTable" v-loading="loading" :data="menuList" row-key="id"
            :default-expand-all="isExpandAll" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" stripe
            highlight-current-row border class="mt4">
            <el-table-column prop="name" label="模块名称" :show-overflow-tooltip="true" width="160"></el-table-column>
            <el-table-column prop="icon" label="图标" align="center" width="100">
               <template #default="scope">
                  <el-image z-index="999999" style="width: 50px; height: 50px" :src="userStore.ossUrl(scope.row.icon)"
                     v-if="scope.row.icon != ''">
                  </el-image>
               </template>
            </el-table-column>
            <el-table-column prop="sort" label="排序" width="60"></el-table-column>
            <el-table-column prop="component" label="组件路径" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column prop="packageName" label="包名" width="250"></el-table-column>
            <el-table-column prop="status" label="状态" width="80">
               <template #default="scope">
                  <DictTag :dictData="sys_common_status" :value="scope.row.status" />
               </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" width="180" prop="createdAt">
               <template #default="scope">
                  <span>{{ parseTime(scope.row.createdAt) }}</span>
               </template>
            </el-table-column>
            <el-table-column label="操作" width="350px" class-name="small-padding fixed-width">
               <template #default="scope">
                  <div class="row-box" style="display: flex; flex-direction: row; align-items: center">
                     <el-button size="small" plain type="primary" icon="Plus" @click="handleAdd(scope.row)"
                        v-auth="['app:menu$add']">新增
                     </el-button>
                     <el-button size="small" plain type="success" icon="Edit" @click="handleUpdate(scope.row)"
                        v-auth="['app:menu$edit']">修改
                     </el-button>
                     <el-button size="small" plain type="danger" icon="Delete" @click="handleDelete(scope.row)"
                        v-auth="['app:menu$remove']">删除
                     </el-button>
                     <el-button size="small" plain type="warning" icon="CircleCheck" @click="handleAuthList(scope.row)"
                        v-auth="['app:menu$auth']">模块授权
                     </el-button>
                  </div>
               </template>
            </el-table-column>
         </el-table>
      </div>
      <!-- 添加或修改菜单对话框 -->
      <el-dialog :title="title" v-model="open" width="680px" append-to-body>
         <el-form ref="menuRef" :model="form" :rules="rules" label-width="100px">
            <el-row>
               <el-col :span="24">
                  <el-form-item label="上级模块">
                     <el-tree-select v-model="form.parentId" :data="menuOptions"
                        :props="{ value: 'id', label: 'name', children: 'children' }" value-key="id"
                        placeholder="选择上级模块" check-strictly />
                  </el-form-item>
               </el-col>
               <el-col :span="24">
                  <el-form-item label="模块名称" prop="name">
                     <el-input v-model="form.name" placeholder="请输入模块名称" />
                  </el-form-item>
               </el-col>
               <el-col :span="24" v-if="form.menuType != 'F'">

                  <el-form-item label="模块图标" prop="icon">
                     <ImageUpload @modelValue="uploadSuccess" :limit="1" :modelValue="form.icon"/>
                  </el-form-item>
               </el-col>
               <el-col :span="24">
                  <el-form-item prop="component">
                     <template #label>
                        <span>
                           <el-tooltip content="访问的组件路径，如：`/system/user/index?type=1`" placement="top">
                              <el-icon><question-filled /></el-icon>
                           </el-tooltip>
                           组件路径
                        </span>
                     </template>
                     <el-input v-model="form.component" placeholder="请输入组件路径" />
                  </el-form-item>
               </el-col>
               <el-col :span="24">
                  <el-form-item>
                     <el-input v-model="form.params" placeholder="请输入参数" maxlength="255" />
                     <template #label>
                        <span>
                           <el-tooltip content='访问路由的默认传递参数，如：`{"id": 1, "name": "poly"}`' placement="top">
                              <el-icon><question-filled /></el-icon>
                           </el-tooltip>
                           参数
                        </span>
                     </template>
                  </el-form-item>
               </el-col>
               <el-col :span="24">
                  <el-form-item label="包名" prop="packageName">
                     <el-input v-model="form.packageName" placeholder="请输入包名" />
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="显示排序" prop="sort">
                     <el-input-number v-model="form.sort" controls-position="right" :min="0" />
                  </el-form-item>
               </el-col>
               <el-col :span="24">
                  <el-form-item>
                     <template #label>
                        <span>
                           <el-tooltip content="选择停用则路由将不会出现在侧边栏，也不能被访问" placement="top">
                              <el-icon><question-filled /></el-icon>
                           </el-tooltip>
                           模块状态
                        </span>
                     </template>
                     <el-radio-group v-model="form.status">
                        <el-radio v-for="dict in sys_common_status" :key="dict.value" :label="dict.value">{{ dict.label
                        }}</el-radio>
                     </el-radio-group>
                  </el-form-item>
               </el-col>
            </el-row>
         </el-form>
         <template #footer>
            <div class="dialog-footer">
               <el-button type="primary" @click="submitForm">确 定</el-button>
               <el-button @click="cancel">取 消</el-button>
            </div>
         </template>
      </el-dialog>


      <el-dialog :title="menuAuthListTitle" v-model="menuAuthListOpen" width="60%" append-to-body>

         <el-row :gutter="10" class="mb4">
            <el-col :span="1.5">
               <el-button type="primary" icon="Plus" v-auth="['app:menu$auth']" @click="handleAuth">授权
               </el-button>
            </el-col>
         </el-row>

         <el-table v-loading="processLoading" fit :data="menuAuthList" border>
            <el-table-column label="序号" align="center" type="index" width="80" />
            <el-table-column label="授权类型" align="center" prop="authTypeDesc" />
            <el-table-column label="授权名称" align="center" prop="authDesc" />
            <el-table-column label="授权时间" align="center" prop="createdAt" />
            <el-table-column label="操作" align="center" width="100" class-name="small-padding fixed-width">
               <template #default="scope">
                  <div class="row-box" style="display: flex; flex-direction: row; align-items: center">
                     <el-button size="small" plain type="danger" icon="Delete" v-auth="['app:menu$authCancel']"
                        @click="handleAuthDelete(scope.row)">取消
                     </el-button>
                  </div>
               </template>
            </el-table-column>
         </el-table>
      </el-dialog>


      <!-- 添加或修改菜单对话框 -->
      <el-dialog :title="menuAuthTitle" v-model="menuAuthOpen" width="500px" append-to-body>
         <el-form ref="menuAuthRef" :model="form" :rules="rules" label-width="100px">
            <el-row>
               <el-col :span="24">
                  <el-form-item label="授权类型" prop="authType">
                     <el-radio-group v-model="form.authType">
                        <el-radio label="1">部门</el-radio>
                        <el-radio label="2">角色</el-radio>
                        <!--                        <el-radio label="3">用户</el-radio>-->
                     </el-radio-group>
                  </el-form-item>
               </el-col>
               <el-col :span="24" v-if="form.authType == '1'">
                  <el-form-item label="授权部门">
                     <el-tree-select v-model="form.authId" :data="deptOptions"
                        :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id"
                        placeholder="选择授权部门" check-strictly />
                  </el-form-item>
               </el-col>
               <el-col :span="24" v-if="form.authType == '2'">
                  <el-form-item label="授权角色">
                     <el-select v-model="form.authId" placeholder="选择授权角色">
                        <el-option v-for="item in roleOptions" :key="item.roleId" :label="item.roleName"
                           :value="item.roleId" :disabled="item.status == 1"></el-option>
                     </el-select>
                  </el-form-item>
               </el-col>
               <!--               <el-col :span="24" v-if="form.authType == '3'">-->
               <!--                  <el-form-item label="授权用户">-->
               <!--                     <el-tree-select-->
               <!--                         v-model="form.authId"-->
               <!--                         :data="menuOptions"-->
               <!--                         :props="{ value: 'id', label: 'name', children: 'children' }"-->
               <!--                         value-key="id"-->
               <!--                         placeholder="选择授权用户"-->
               <!--                         check-strictly-->
               <!--                     />-->
               <!--                  </el-form-item>-->
               <!--               </el-col>-->
            </el-row>
         </el-form>
         <template #footer>
            <div class="dialog-footer">
               <el-button type="primary" @click="submitAuthForm">确 定</el-button>
               <el-button @click="handleAuthCancel">取 消</el-button>
            </div>
         </template>
      </el-dialog>
   </div>
</template>

<script setup name="Menu">
import apiAppmenu from "@/api/system/appmenu";
// import SvgIcon from "@/components/SvgIcon";
import useUserStore from '@/store/modules/user'
import apiUser from '@/api/system/user'
const { proxy } = getCurrentInstance();
const userStore = useUserStore();
const { sys_common_status } = proxy.useDict("sys_common_status");

const menuList = ref([]);
const open = ref(false);
const loading = ref(false);
const title = ref("");
const menuOptions = ref([]);
const isExpandAll = ref(false);
const refreshTable = ref(true);
const showChooseIcon = ref(false);
const iconSelectRef = ref(null);
const menuAuthList = ref([]);
const menuAuthListOpen = ref(false);
const menuAuthListTitle = ref("");
const menuAuthOpen = ref(false);
const menuAuthTitle = ref("");
const deptOptions = ref([]);
const roleOptions = ref([]);

const processLoading = ref(true);

const authMenuId = ref(null);

const data = reactive({
   form: {},
   queryParams: {
      name: undefined
   },
   rules: {
      name: [{ required: true, message: "模块名称不允许为空", trigger: "blur" }],
      sort: [{ required: true, message: "模块顺序不允许为空", trigger: "blur" }]
   },
});



const { queryParams, form, rules } = toRefs(data);


/** 查询模块列表 */
function getList() {
   // loading.value = true;
   apiAppmenu.list(queryParams.value).then(response => {
      menuList.value = proxy.handleTree(response.data, "id");
   }).finally(() => {
    loading.value = false
  })
}
/** 查询模块下拉树结构 */
function getTreeselect() {
   menuOptions.value = [];
   apiAppmenu.list().then(response => {
      const menu = { id: 0, name: "主模块", children: [] };
      menu.children = proxy.handleTree(response.data, "id");
      menuOptions.value.push(menu);
   });
}
/** 取消按钮 */
function cancel() {
   open.value = false;
   reset();
}
/** 表单重置 */
function reset() {
   form.value = {
      id: undefined,
      parentId: 0,
      name: undefined,
      icon: "",
      sort: undefined,
      status: "0"
   };
   proxy.resetForm("menuRef");
}
/** 展示下拉图标 */
function showSelectIcon() {
   iconSelectRef.value.reset();
   showChooseIcon.value = true;
}
/** 选择图标 */
function selected(name) {
   form.value.icon = name;
   showChooseIcon.value = false;
}
/** 图标外层点击隐藏下拉列表 */
function hideSelectIcon(event) {
   var elem = event.relatedTarget || event.srcElement || event.target || event.currentTarget;
   var className = elem.className;
   if (className !== "el-input__inner") {
      showChooseIcon.value = false;
   }
}
/** 搜索按钮操作 */
function handleQuery() {
   getList();
}
/** 重置按钮操作 */
function resetQuery() {
   proxy.resetForm("queryRef");
   handleQuery();
}
/** 新增按钮操作 */
function handleAdd(row) {
   reset();
   getTreeselect();
   if (row != null && row.id) {
      form.value.parentId = row.id;
   } else {
      form.value.parentId = 0;
   }
   open.value = true;
   title.value = "添加模块";
}



/** 授权按钮操作 */
function handleAuth() {
   menuAuthOpen.value = true;
   menuAuthTitle.value = "模块授权";
}
/** 取消按钮 */
function handleAuthCancel() {
   menuAuthOpen.value = false;
}
function getAuthList() {
   processLoading.value = true;
   apiAppmenu.listAuth({ menuId: authMenuId.value }).then(response => {
      menuAuthList.value = response.data;
      processLoading.value = false;
   });
}
function handleAuthList(row) {
   menuAuthListOpen.value = true;
   menuAuthListTitle.value = "模块授权列表 【" + row.name + "】";
   authMenuId.value = row.id;
   getAuthList();
}



/** 展开/折叠操作 */
function toggleExpandAll() {
   refreshTable.value = false;
   isExpandAll.value = !isExpandAll.value;
   nextTick(() => {
      refreshTable.value = true;
   });
}
/** 修改按钮操作 */
async function handleUpdate(row) {
   reset();
   await getTreeselect();
   apiAppmenu.getById(row.id).then(response => {
      response.data.status = response.data.status + "";
      form.value = response.data;
      open.value = true;
      title.value = "修改模块";
   });
}
/** 提交按钮 */
function submitForm() {
   proxy.$refs["menuRef"].validate(valid => {
      if (valid) {
         if (form.value.id != undefined) {
            apiAppmenu.update(form.value).then(response => {
               proxy.$modal.success("修改成功");
               open.value = false;
               getList();
            });
         } else {
            apiAppmenu.add(form.value).then(response => {
               proxy.$modal.success("新增成功");
               open.value = false;
               getList();
            });
         }
      }
   });
}
function submitAuthForm() {
   proxy.$refs["menuAuthRef"].validate(valid => {
      if (valid) {
         form.value.menuIdList = [authMenuId.value];
         apiAppmenu.addAuth(form.value).then(response => {
            proxy.$modal.success("授权成功");
            menuAuthOpen.value = false;
            getAuthList();
         });
      }
   });
}


/** 删除按钮操作 */
function handleDelete(row) {
   proxy.$modal.confirm('是否确认删除名称为"' + row.name + '"的数据项?').then(function () {
      return apiAppmenu.delete(row.id);
   }).then(() => {
      getList();
      proxy.$modal.success("删除成功");
   }).catch(() => { });
}
function handleAuthDelete(row) {
   proxy.$modal.confirm('是否确认取消“【' + row.authTypeDesc + '】' + row.authDesc + '”的授权?').then(function () {
      return apiAppmenu.deleteAuth(row.id);
   }).then(() => {
      getAuthList();
      proxy.$modal.success("取消授权成功");
   }).catch(() => { });
}

function getDeptTree() {
   apiUser.deptTreeSelect().then(response => {
      deptOptions.value = response.data;
   });
};

function getRoleList() {
   apiUser.getUserRoleList().then(response => {
      roleOptions.value = response.data;
   });
};


/**
 * 上传图片回调
 */
function uploadSuccess(val) {
   form.value.icon = val
}
getDeptTree();
getRoleList();
getList();
</script>
